<?php

namespace app\service;

use Predis\Client;

class RedisService
{
    private static $instance = null;
    private $client = null;

    private function __construct()
    {
        // 直接使用配置，避免config函数问题
        $this->client = new Client([
            'scheme' => 'tcp',
            'host' => '127.0.0.1',
            'port' => 6379,
            'password' => null,
            'database' => 0,
            'timeout' => 5,
            'read_timeout' => 0,
            'persistent' => false,
        ]);
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * 获取新的Redis实例（用于独立连接，如订阅）
     */
    public static function getNewInstance()
    {
        return new self();
    }

    public function getClient()
    {
        return $this->client;
    }

    /**
     * 生成房间代码
     */
    public function generateRoomCode()
    {
        $key = 'room_code_counter';
        
        // 使用Redis自增计数器
        $counter = $this->client->incr($key);
        
        // 如果计数器超过999999，重置为1
        if ($counter > 999999) {
            $this->client->set($key, 1);
            $counter = 1;
        }
        
        // 格式化为6位数字，前缀为8x
        return '8x' . str_pad($counter, 6, '0', STR_PAD_LEFT);
    }

    /**
     * 检查房间代码是否存在
     */
    public function roomCodeExists($roomCode)
    {
        $key = "room_code:{$roomCode}";
        return $this->client->exists($key);
    }

    /**
     * 设置房间代码缓存
     */
    public function setRoomCode($roomCode, $roomId, $ttl = 86400)
    {
        $key = "room_code:{$roomCode}";
        $this->client->setex($key, $ttl, $roomId);
    }

    /**
     * 获取房间ID
     */
    public function getRoomId($roomCode)
    {
        $key = "room_code:{$roomCode}";
        return $this->client->get($key);
    }

    /**
     * 删除房间代码缓存
     */
    public function deleteRoomCode($roomCode)
    {
        $key = "room_code:{$roomCode}";
        $this->client->del($key);
    }

    /**
     * 获取缓存数据
     */
    public function get($key)
    {
        return $this->client->get($key);
    }

    /**
     * 设置缓存数据
     */
    public function set($key, $value, $ttl = null)
    {
        if ($ttl) {
            return $this->client->setex($key, $ttl, $value);
        } else {
            return $this->client->set($key, $value);
        }
    }

    /**
     * 删除缓存数据
     */
    public function del($key)
    {
        return $this->client->del($key);
    }

    /**
     * 检查键是否存在
     */
    public function exists($key)
    {
        return $this->client->exists($key);
    }
}
